<template>
    <view class="address-edit">
        <wd-cell-group>
            <!-- 地区选择 -->
            <view class="area-row">
                <wd-picker :columns="columns" v-model="value" :column-change="onChangeDistrict"
                    :display-format="displayFormat" @confirm="handleConfirm" class="area-picker" :loading="loading"
                    column-num="4">
                </wd-picker>
                <view class="default-switch">
                    <wd-switch v-model="form.isDefault" size="20px" />
                    <text>默认</text>
                </view>
            </view>

            <!-- 详细地址 -->
            <wd-input v-model="form.address" type="textarea" placeholder="请输入详细地址，如街道、楼牌号等" maxlength="100">
                <template #label>
                    <view class="label-with-required">
                        <text class="required">*</text>
                        <text>详细地址</text>
                    </view>
                </template>
            </wd-input>

            <!-- 联系人信息 -->
            <wd-input v-model="form.contactName" placeholder="请输入收货人姓名" clearable>
                <template #label>
                    <view class="label-with-required">
                        <text class="required">*</text>
                        <text>收货人</text>
                    </view>
                </template>
            </wd-input>
            <wd-input v-model="form.contactPhone" placeholder="请输入手机号码" type="number" clearable>
                <template #label>
                    <view class="label-with-required">
                        <text class="required">*</text>
                        <text>手机号码</text>
                    </view>
                </template>
            </wd-input>
        </wd-cell-group>

        <!-- 底部按钮 -->
        <view class="bottom-button">
            <wd-button type="primary" block @click="saveAddress">保存</wd-button>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getRegionMap, saveAddressAPI } from '@/api/address'

// 表单数据
const form = ref({
    contactName: '',
    contactPhone: '',
    province: '',
    city: '',
    district: '',
    street: '',
    address: '',
    isDefault: false
})

// 修改地区数据结构的获取和处理
const district = ref({})
const value = ref([]) // 修改为四级默认值
const columns = ref([])

// 添加 loading 状态
const loading = ref(false)

// 获取地区数据
const getDistrictData = async (addressData = null) => {
    loading.value = true
    try {
        const res = await getRegionMap()
        district.value = res

        if (addressData) {
            // 编辑模式：根据已有地址数据初始化列数据
            const provinceList = district.value['0']
            const cityList = district.value[addressData.provinceId]
            const districtList = district.value[addressData.cityId]
            const streetList = district.value[addressData.districtId]

            // 设置四列数据
            columns.value = [
                provinceList,
                cityList,
                districtList,
                streetList
            ]
        } else {
            // 新增模式：使用默认的第一项
            columns.value = [
                district.value['0'],
                district.value[district.value['0'][0].value],
                district.value[district.value[district.value['0'][0].value][0].value],
                district.value[district.value[district.value[district.value['0'][0].value][0].value][0].value]
            ]
        }
    } catch (error) {
        uni.showToast({
            title: '获取地区数据失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

// 修改列变化处理函数支持四级
const onChangeDistrict = (pickerView, value, columnIndex, resolve) => {
    const item = value[columnIndex]
    if (columnIndex === 0) {
        // 省份改变，更新市、区、街道
        pickerView.setColumnData(1, district.value[item.value])
        pickerView.setColumnData(2, district.value[district.value[item.value][0].value])
        pickerView.setColumnData(3, district.value[district.value[district.value[item.value][0].value][0].value])
    } else if (columnIndex === 1) {
        // 城市改变，更新区、街道
        pickerView.setColumnData(2, district.value[item.value])
        pickerView.setColumnData(3, district.value[district.value[item.value][0].value])
    } else if (columnIndex === 2) {
        // 区改变，更新街道
        pickerView.setColumnData(3, district.value[item.value])
    }
    resolve()
}

// 修改显示格式化函数
const displayFormat = (items) => {
    if (!items || !items.length) return ''
    return items.map(item => item.label).join('-')
}

// 修改确认选择处理函数支持四级
const handleConfirm = (items) => {
    let { selectedItems } = items
    if (selectedItems && selectedItems.length === 4) {
        form.value.provinceId = selectedItems[0].value
        form.value.cityId = selectedItems[1].value
        form.value.districtId = selectedItems[2].value
        form.value.streetId = selectedItems[3].value
    }
}

// 修改编辑模式的地址详情处理
onLoad(async (options) => {
    if (options.address) {
        const addressData = JSON.parse(decodeURIComponent(options.address))
        form.value = {
            ...addressData,
            isDefault: addressData.isDefault === 1
        }
        // 先初始化地区数据，传入地址信息
        await getDistrictData(addressData)
        // 设置选择器的值
        value.value = [
            addressData.provinceId,
            addressData.cityId,
            addressData.districtId,
            addressData.streetId
        ]
    } else {
        await getDistrictData()
    }
})

// 修改保存地址方法
const saveAddress = async () => {
    // 表单验证
    if (!form.value.contactName) {
        uni.showToast({
            title: '请输入收货人姓名',
            icon: 'none'
        })
        return
    }
    if (!form.value.contactPhone) {
        uni.showToast({
            title: '请输入手机号码',
            icon: 'none'
        })
        return
    }
    if (!form.value.provinceId && form.value.provinceId !== 0) {
        uni.showToast({
            title: '请选择所在省',
            icon: 'none'
        })
        return
    }
    if (!form.value.cityId && form.value.cityId !== 0) {
        uni.showToast({
            title: '请选择所在市',
            icon: 'none'
        })
        return
    }
    if (!form.value.districtId && form.value.districtId !== 0) {
        uni.showToast({
            title: '请选择所在区',
            icon: 'none'
        })
        return
    }
    if (!form.value.streetId && form.value.streetId !== 0) {
        uni.showToast({
            title: '请选择所在街道',
            icon: 'none'
        })
        return
    }
    if (!form.value.address) {
        uni.showToast({
            title: '请输入详细地址',
            icon: 'none'
        })
        return
    }

    try {
        uni.showLoading({
            title: '保存中...'
        })

        // 构造请求参数，确保 id 为 long 类型
        const params = {
            id: form.value.id ? parseInt(form.value.id) : null,  // 确保转换为数字类型
            provinceId: parseInt(form.value.provinceId),
            cityId: parseInt(form.value.cityId),
            districtId: parseInt(form.value.districtId),
            streetId: parseInt(form.value.streetId),
            address: form.value.address,
            contactName: form.value.contactName,
            contactPhone: form.value.contactPhone,
            isDefault: form.value.isDefault ? 1 : 0
        }
        const res = await saveAddressAPI(params)

        if (res) {
            uni.showToast({
                title: '保存成功',
                icon: 'success'
            })

            // 直接返回即可，因为列表页面的 onShow 会自动刷新数据
            uni.navigateBack({
                delta: 1
            })
        } else {
            uni.showToast({
                title: '保存失败',
                icon: 'none'
            })
        }
    } catch (error) {
        uni.showToast({
            title: error.message || '保存失败',
            icon: 'none'
        })
    } finally {
        uni.hideLoading()
    }
}
</script>

<style lang="scss">
.address-edit {
    min-height: 100vh;
    background: #f8f8f8;
    padding-bottom: 120rpx;
}

.area-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    background: #fff;
    border-bottom: 1px solid #eee;

    .area-picker {
        flex: 1;
    }

    .picker-content {
        display: flex;
        align-items: center;

        .required {
            color: #fa4350;
            margin-right: 4rpx;
        }

        .label {
            font-size: 28rpx;
            color: #333;
            margin-right: 20rpx;
        }

        .value {
            font-size: 28rpx;
            color: #666;
        }
    }

    .default-switch {
        display: flex;
        align-items: center;
        margin-left: 20rpx;

        text {
            font-size: 24rpx;
            color: #666;
            margin-left: 8rpx;
        }
    }
}

.bottom-button {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx;
    background: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.label-with-required {
    display: flex;
    align-items: center;
}

.required {
    color: #fa4350;
    margin-right: 4rpx;
}
</style>